import { Button } from 'antd';
import { PageContainer } from '@ant-design/pro-layout';
import type { ProColumns, ActionType } from '@ant-design/pro-table';
import { history, getDvaApp } from 'umi';
import ProTable from '@ant-design/pro-table';
import type { ProFormInstance } from '@ant-design/pro-form';
import { useRef, useEffect, useState } from 'react';
import moment from 'moment';
import $utils from '@/utils/utils';
import { weChatOrderStat } from '@/services/dateMange';
type GithubIssueItem = {
  id: number;
  index: number;
  createDate: string;
  delivery: number;
  pickup: number;
  pickupNotice: number;
  pickupSucNotice: number;
};

const initDate = {
  startDate: moment().subtract(1, 'days').startOf('day'), //  开始时间
  endDate: moment().subtract(1, 'days').endOf('days'), // 结束时间
};

const WeChatstat: React.FC = () => {
  const actionRef = useRef<ActionType>();
  const formRef = useRef<ProFormInstance>();
  // 解决无法调用dispatch
  const dispatch = getDvaApp()._store.dispatch;

  const [initParams, setParams] = useState<any>();
  const [current, setCurrent] = useState<number>(1);
  const [pageSize, setPageSize] = useState<number>(20);
  const [total, setTotal] = useState<number>(0);
  const l_state: any = history.location.state;

  useEffect(() => {
    $utils.addTab(dispatch, {
      name: '微信数据统计',
      path: '/DateMange/WeChatstat',
      isTopMenu: true,
      state: {},
    });
    if (!initParams) {
      const startDate = l_state?.startDate ? moment(l_state.startDate) : initDate.startDate;
      const endDate = l_state?.endDate ? moment(l_state.endDate) : initDate.endDate;
      setParams({
        dateTime: [startDate, endDate],
      });
    }
  }, []);

  const columns: ProColumns<GithubIssueItem>[] = [
    {
      title: '日期',
      dataIndex: 'dateTime',
      hideInTable: true,
      valueType: 'dateRange',
      colSize: 1.5,
      search: {
        transform: (value: any) => ({ startDate: value[0], endDate: value[1] }),
      },
      fieldProps: {
        disabledDate: (current: any) => {
          // 只可选择90天内，上线日期后
          return !(
            current > moment('06-14-2022', 'MM-DD-YYYY').endOf('days') &&
            current > moment().subtract(24, 'month') &&
            current < moment().subtract(1, 'days').endOf('days')
          );
        },
        ranges: {
          今天: [moment().startOf('day'), moment().endOf('day')],
          昨天: [
            moment().subtract(1, 'days').startOf('day'),
            moment().subtract(1, 'days').endOf('day'),
          ],
          上月: [
            moment(moment().subtract({ day: new Date().getDate() - 1, month: 1 })),
            moment(moment().subtract({ day: new Date().getDate(), month: 0 })),
          ],
        },
      },
    },
    {
      title: '日期',
      dataIndex: 'createDate',
      search: false,
    },
    {
      title: '投递数',
      dataIndex: 'delivery',
      search: false,
    },
    {
      title: '取件数',
      dataIndex: 'pickup',
      search: false,
    },
    {
      title: '取件通知发送数',
      dataIndex: 'pickupNotice',
      search: false,
    },
    {
      title: '取件成功通知发送数',
      dataIndex: 'pickupSucNotice',
      search: false,
    },
  ];

  return (
    <PageContainer>
      {initParams && (
        <ProTable<GithubIssueItem>
          columns={columns}
          actionRef={actionRef}
          formRef={formRef}
          rowKey="index"
          form={{
            initialValues: initParams,
          }}
          search={{
            span: 6,
            optionRender: (searchConfig, formProps, dom) => [
              dom.reverse()[0],
              <Button
                key="resetText"
                onClick={() => {
                  formRef?.current?.setFieldsValue({
                    dateTime: [initDate.startDate, initDate.endDate],
                  });
                }}
              >
                重置
              </Button>,
            ],
          }}
          options={{
            setting: {
              listsHeight: 400,
            },
          }}
          pagination={{
            pageSize: pageSize,
            showSizeChanger: true,
            size: 'small',
            total: total,
            onShowSizeChange: (current, pageSize) => {
              setCurrent(current);
              setPageSize(pageSize);
            },
          }}
          onSubmit={() => {}}
          request={async (data) => {
            const params = {
              current,
              pageSize,
              startDate: data?.startDate || '',
              endDate: data?.endDate || '',
            };
            console.log('weChatOrderStat', params);
            const msg = await weChatOrderStat(params);
            $utils.addTab(dispatch, {
              name: '微信数据统计',
              path: '/DateMange/WeChatstat',
              isTopMenu: true,
              state: params,
            });
            setParams(params);
            setTotal(msg.body?.count);
            return {
              data: (msg.body?.list || []).map((item: object, index: number) => ({
                ...item,
                index: index + 1,
              })),
              success: msg.code === 0,
            };
          }}
        />
      )}
    </PageContainer>
  );
};

export default WeChatstat;
